<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/01/24 13:22:15 $)
// $RCSfile: osc.login.php,v $ : $Revision: 1.2 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Initialization function. You can connect to your database etc over here.
*/
function loginShareInit()
{
	global $loginshare;

	$loginshare->moduleloaded = true;
}

/**
* Authorize a user based on email and password
*/
function loginShareAuthorize($username, $password)
{
	global $dbCore, $_SWIFT, $loginshare, $settings;

	$_loginshare = $settings->getSection("loginshare");
	$dbLoginShare = new dbCore($_loginshare["oschostname"], $_loginshare["oscdbuser"], $_loginshare["oscdbpass"], $_loginshare["oscdbname"], "mysql", false);

	$_user = $dbLoginShare->queryFetch("SELECT * FROM `customers` WHERE `customers_email_address` = '". $dbCore->escape($username) ."';");
	if (empty($_user["customers_id"]))
	{
		return false;
	}

    // Prepare provided password for check

      // split apart the hash / salt
      $stack = explode(':', $_user["customers_password"]);

      if (sizeof($stack) != 2)
      {
        return false;
      }

	$userpassword = md5($stack[1] . $password);
    $checkpassword = $stack[0];

	$regpassword = md5($password);

	if ($checkpassword == $userpassword && !empty($_user["customers_password"]))
	{
		$userid = getLoginShareUser(LOGINAPI_OSC, $_user["customers_id"]);
		if (!$userid)
		{
			// Not registered, Register him
			$userid = insertUser(true, $_user["customers_email_address"], $regpassword, $_SWIFT["tgroup"]["regusergroupid"], LOGINAPI_OSC, $_user["customers_id"], $_user["customers_firstname"]." ".$_user["customers_lastname"], $_SWIFT["tgroup"]["languageid"], 0, false, 1, true, true);
		}

		if (!$userid)
		{
			// ======= GET THE USER WITH THE EMAIL AND TAG HIM UNDER MODERNBILL =======
			$_swiftuser = $dbCore->queryFetch("SELECT `userid` FROM `". TABLE_PREFIX ."useremails` WHERE `email` = '". $dbCore->escape($_user["customers_email_address"]) ."' LIMIT 1;");
			if (!empty($_swiftuser["userid"]))
			{
				$dbCore->query("UPDATE `". TABLE_PREFIX ."users` SET `loginapi_moduleid` = '". LOGINAPI_OSC ."', `loginapi_userid` = '". intval($_user["customers_id"]) ."' WHERE `userid` = '". intval($_swiftuser["userid"]) ."';");

				$userid = $_swiftuser["userid"];
			} else {
				return false;
			}
		}

		$_swiftuser = $loginshare->loadSWIFTUser($userid);
		if (!$_swiftuser)
		{
			return false;
		}

		$_SWIFT["user"] = $_swiftuser;

		return $_swiftuser["userid"];
	} else {
		// Failed Authentication, Fall back over to default SupportSuite Login Routine
		$_email = $dbCore->queryFetch("SELECT `userid` FROM `". TABLE_PREFIX ."useremails` WHERE `email` = '". $dbCore->escape($username) ."';");
		if (empty($_email["userid"]))
		{
			return false;
		}

		$_user = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."users` WHERE `userid` = '". intval($_email["userid"]) ."';");

		if ($_user["userpassword"] == md5($password) && $_user["enabled"] == 1)
		{
			// Authenticated
			$_SWIFT["user"] = $_user;

			return $_user["userid"];
		} else {
			unset($_SWIFT["user"]);
		}		
	}

	return false;
}

/**
* Return the Unique User ID of the current user
*/
function loginShareUserID()
{
	global $_SWIFT;

	if (empty($_SWIFT["user"]["userid"]))
	{
		return false;
	} else {
		return $_SWIFT["user"]["userid"];
	}
}

/**
* Logout the current user
*/
function loginShareLogout()
{
	global $session, $_SWIFT;

	$session->updateSession($_SWIFT["session"]["sessionid"], 0);

	return true;
}

/**
* Load the user credentials into current workspace. The following variables should be declared for proper working:
* userid - User id that is set in the "users" table
* fullname
* email - Array
* password (MD5 Hashed)
* usergroupid - If this is not set, then it will use the default registered user group for this template group
*/
function loginShareLoadUser()
{
	global $dbCore, $_SWIFT, $loginshare;

	if (empty($_SWIFT["session"]["typeid"]))
	{
		$_SWIFT["user"]["loggedin"] = false;
		return false;
	}

	$_user = $loginshare->loadSWIFTUser($_SWIFT["session"]["typeid"]);
	if (!$_user)
	{
		$_SWIFT["user"]["loggedin"] = false;

		return false;
	}

	$_SWIFT["user"] = $_user;

	return true;
}

/**
* Renders the Login Share Form
*/
function renderLoginShareForm()
{
	global $_SWIFT;

	$forms = array();

	$forms[0]["title"] = $_SWIFT["language"]["hostname"];
	$forms[0]["name"] = "oschostname";
	$forms[1]["title"] = $_SWIFT["language"]["dbname"];
	$forms[1]["name"] = "oscdbname";
	$forms[2]["title"] = $_SWIFT["language"]["dbuser"];
	$forms[2]["name"] = "oscdbuser";
	$forms[3]["title"] = $_SWIFT["language"]["dbpass"];
	$forms[3]["name"] = "oscdbpass";

	return $forms;

}
?>
